import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { House, HouseDocument } from './schemas/house.schema';
import { CreateHouseDto } from './dto/create-house.dto';

@Injectable()
export class HouseService {
  constructor(
    @InjectModel(House.name) private houseModel: Model<HouseDocument>,
  ) {}

  async create(createHouseDto: CreateHouseDto): Promise<House> {
    const createdHouse = new this.houseModel(createHouseDto);
    return createdHouse.save();
  }

  async createBatch(createHouseDtos: CreateHouseDto[]): Promise<House[]> {
    const houses = await this.houseModel.insertMany(createHouseDtos);
    return houses;
  }

  async findAll(): Promise<House[]> {
    return this.houseModel.find().sort({ timestamp: -1 }).exec();
  }

  async findById(id: string): Promise<House> {
    return this.houseModel.findById(id).exec();
  }

  async findByTimeRange(startTime: number, endTime: number): Promise<House[]> {
    return this.houseModel
      .find({
        timestamp: {
          $gte: startTime,
          $lte: endTime,
        },
      })
      .sort({ timestamp: -1 })
      .exec();
  }

  async count(): Promise<number> {
    return this.houseModel.countDocuments().exec();
  }

  async deleteById(id: string): Promise<House> {
    return this.houseModel.findByIdAndDelete(id).exec();
  }
}